package com.opennetexam.manager.utils;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * @author 奶茶
 * Created by on 2018/8/14.
 */
public class Base64Util {

    /**
     * String -> base64
     * @param str
     * @return
     */
    public static String getBase64(String str) {
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            s = new BASE64Encoder().encode(b);
        }
        return s;
    }

    /**
     * base64 -> String
     * @param s
     * @return
     */
    public static String getFromBase64(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String fileTOBase64(String filePath) {
        File f = new File(filePath);

        try {
            try(ByteArrayOutputStream os = new ByteArrayOutputStream((int)f.length());
                BufferedInputStream fis = new BufferedInputStream(new FileInputStream(f))) {

                byte[] buff = new byte[3072];
                int size;
                while ((size = fis.read(buff)) != -1) {
                    os.write(buff, 0, size);
                }
                return Base64.encodeBase64String(os.toByteArray());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        String str = "我爱你";
        String base64 = getBase64(str);

        String fromBase64 = getFromBase64(base64);
        System.out.println(fromBase64);
    }
}
